import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { 
  SDTemplate, 
  TemplateType, 
  TemplateListResponse, 
  TemplateResponse,
  CreateTemplateRequest,
  TemplateQueryParams 
} from '@/types/templates';
import { validateTemplate, validateTemplateForCreate, sanitizeTemplate, generateUniqueId } from '@/utils/templateValidation';

const COLLECTION_NAME = 'sd_templates';

/**
 * GET /api/templates-db
 * 获取模板列表，支持分页、筛选、搜索
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type') as TemplateType | null;
    const page = parseInt(searchParams.get('page') || '1');
    const pageSize = Math.min(parseInt(searchParams.get('pageSize') || '50'), 100);
    const search = searchParams.get('search') || '';
    const sortBy = searchParams.get('sortBy') || 'created_at';
    const sortOrder = searchParams.get('sortOrder') || 'desc';

    const db = await getDb();
    
    // 构建查询条件
    const filter: any = {};
    if (type && Object.values(TemplateType).includes(type)) {
      filter.type = type;
    }

    // 获取总数
    const countResult = await db.count(COLLECTION_NAME, filter);
    const total = countResult.data || 0;

    // 获取数据
    const queryOptions = {
      page,
      pageSize,
      sortBy,
      sortOrder: sortOrder as 'asc' | 'desc'
    };

    const result = await db.findMany<SDTemplate>(COLLECTION_NAME, filter, queryOptions);
    
    if (!result.success) {
      return NextResponse.json({
        success: false,
        error: result.error || '获取模板列表失败'
      } as TemplateListResponse, { status: 500 });
    }

    let templates = result.data || [];

    // 客户端搜索过滤（如果数据库不支持复杂搜索）
    if (search) {
      const searchLower = search.toLowerCase();
      templates = templates.filter(template => 
        template.name.toLowerCase().includes(searchLower) ||
        template.description.toLowerCase().includes(searchLower) ||
        template.id.toLowerCase().includes(searchLower)
      );
    }

    return NextResponse.json({
      success: true,
      data: templates,
      total,
      page,
      pageSize
    } as TemplateListResponse);

  } catch (error: any) {
    console.error('获取模板列表失败:', error);
    return NextResponse.json({
      success: false,
      error: error.message || '服务器内部错误'
    } as TemplateListResponse, { status: 500 });
  }
}

/**
 * POST /api/templates-db
 * 创建新模板
 */
export async function POST(request: NextRequest) {
  try {
    const body: CreateTemplateRequest = await request.json();
    const { template } = body;

    if (!template) {
      return NextResponse.json({
        success: false,
        error: '模板数据不能为空'
      } as TemplateResponse, { status: 400 });
    }

    // 数据清理和标准化
    const sanitizedTemplate = sanitizeTemplate(template);

    // 数据验证（创建操作不需要id）
    const validation = validateTemplateForCreate(sanitizedTemplate);
    if (!validation.isValid) {
      return NextResponse.json({
        success: false,
        error: '数据验证失败',
        details: validation.errors
      }, { status: 400 });
    }

    const db = await getDb();

    // 检查ID是否已存在，如果没有ID则生成一个
    let templateId = sanitizedTemplate.id;
    if (!templateId) {
      // 获取现有ID列表
      const existingResult = await db.findMany<SDTemplate>(COLLECTION_NAME, {});
      const existingIds = existingResult.data?.map(t => t.id) || [];
      templateId = generateUniqueId(sanitizedTemplate.name || 'template', existingIds);
    } else {
      // 检查ID唯一性
      const existingTemplate = await db.findOne<SDTemplate>(COLLECTION_NAME, { id: templateId });
      if (existingTemplate.data) {
        return NextResponse.json({
          success: false,
          error: `ID "${templateId}" 已存在`
        } as TemplateResponse, { status: 409 });
      }
    }

    // 创建完整的模板对象
    const now = new Date().toISOString();
    const newTemplate: SDTemplate = {
      ...sanitizedTemplate,
      id: templateId,
      created_at: now,
      updated_at: now
    } as SDTemplate;

    // 保存到数据库
    const createResult = await db.create<SDTemplate>(COLLECTION_NAME, newTemplate);
    
    if (!createResult.success) {
      return NextResponse.json({
        success: false,
        error: createResult.error || '创建模板失败'
      } as TemplateResponse, { status: 500 });
    }

    return NextResponse.json({
      success: true,
      data: createResult.data
    } as TemplateResponse, { status: 201 });

  } catch (error: any) {
    console.error('创建模板失败:', error);
    return NextResponse.json({
      success: false,
      error: error.message || '服务器内部错误'
    } as TemplateResponse, { status: 500 });
  }
}

/**
 * DELETE /api/templates-db
 * 批量删除模板
 */
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const idsParam = searchParams.get('ids');
    
    const db = await getDb();
    let deleteResult;
    
    if (!idsParam) {
      // 没有提供ID参数时，清空所有模板
      deleteResult = await db.deleteMany(COLLECTION_NAME, {});
    } else {
      // 提供了ID参数时，删除指定模板
      const ids = idsParam.split(',').map(id => id.trim()).filter(id => id);
      if (ids.length === 0) {
        return NextResponse.json({
          success: false,
          error: 'ID列表不能为空'
        }, { status: 400 });
      }
      
      deleteResult = await db.deleteMany(COLLECTION_NAME, { 
        id: { $in: ids } // MongoDB风格，SQLite实现会转换
      });
    }

    if (!deleteResult.success) {
      return NextResponse.json({
        success: false,
        error: deleteResult.error || '删除模板失败'
      }, { status: 500 });
    }

    const message = !idsParam 
      ? `成功清空所有模板，共删除 ${deleteResult.data || 0} 个模板`
      : `成功删除 ${deleteResult.data || 0} 个模板`;

    return NextResponse.json({
      success: true,
      message,
      deletedCount: deleteResult.data || 0
    });

  } catch (error: any) {
    console.error('批量删除模板失败:', error);
    return NextResponse.json({
      success: false,
      error: error.message || '服务器内部错误'
    }, { status: 500 });
  }
}